<template>
  <el-container>
    <el-aside style="float:left;width: 300px;">
      <el-card class="box-card el-card-flex">
        <!--树状图搜索框 -->
        <div slot="header" class="clearfix">
          <div v-if="selectTreeBox==true">
            <el-select class='top-select' @change="changSelectTree" v-model="selectTreeId" placeholder="请选择">
              <el-option v-for="item in rootTreeData" :key="item.treeId" :label="item.orgName" :value="item.treeId">
              </el-option>
            </el-select>
            <i title="搜索" @click='treeSearch' class="el-icon-search el-icon--right plus-icon" style='text-align: right;'></i>
          </div>
          <el-input v-else ref='searchFcus' v-model="orgNameSearch" @blur='searchBlur' placeholder="请搜索..." suffix-icon="el-icon-search"></el-input>
        </div>
        <div class="text item el-over-auto">
          <div v-if="initTree">
            <el-tree ref='tree' v-if="!orgNameSearch" :load="loadNode" node-key="id" :props="defaultProps"
              :highlight-current="true" lazy @node-click="handleNodeClick" :current-node-key="currentNodekey"
              :default-expanded-keys="expandedkeys" :key='treeKey'>
            </el-tree>
            <el-tree ref='tree' v-if="orgNameSearch" :data="searchTreeData" node-key="id" :props="defaultProps"
              :highlight-current="true" @node-click="handleNodeClick" default-expand-all>
            </el-tree>
          </div>
        </div>
      </el-card>
    </el-aside>
    <el-main style="padding:0 0 0 10px;">
      <div class="el-full el-box-column">
        <el-tabs class="el-tabs-bg el-box-column el-flex el-tabs-flex" v-model="activeName">
          <!-- 员工信息-->
          <el-tab-pane label="人员信息" name="first" class="el-flex el-box-column">
            <div class="demo-form-inline" style="float: left;height:43px">
              <!-- 员工搜索 -->
              <el-input clearable v-model="personalSearch" placeholder="请输入员工姓名" style="width:200px;"
                @keyup.enter.native="originalEmployeeTableSearch" @clear="clearSeachPeople">
                <el-button slot="append" icon="el-icon-search" @click="originalEmployeeTableSearch"></el-button>
              </el-input>
              <el-button plain type="primary" style="float: right;margin-right:5px; margin-left:5px" class="el-button-pad"
                @click="handleAdd">新增<i class="el-icon-plus el-icon--right"></i>
              </el-button>
              <el-button plain type="primary" style="float: right;margin-right: 5px; margin-left:5px" class="el-button-pad"
                @click="relatedStaff">
                关联员工
                <i class="el-icon-paperclip el-icon--right"></i>
              </el-button>
            </div>
            <div class="el-flex el-box-column">
              <el-table border height="100%" :data="tableData" stripe ref="tableData">
                <el-table-column type="index" min-width="55px" label="序号" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column prop="empName" min-width="100px" label="人员姓名" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column prop="cardNo" min-width="85px" label="证件号" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column prop="empCode" min-width="100px" label="人员代码" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column prop="gender" min-width="70px" label="性别" align="center" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <span v-if='scope.row.archive&&scope.row.archive.gender'>{{scope.row.archive.gender=='8173e2cf8a034ec8ba575d31341ab449'?"男":"女"}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="empStatus" min-width="100px" label="人员状态" align="center" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <span v-if='scope.row.orgRelations&&scope.row.orgRelations[0]&&scope.row.orgRelations[0].empStatus'
                      v-for="item in staffStatusDatas" :key='item.id'>{{scope.row.orgRelations[0].empStatus==item.id?item.name:''}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="userName" min-width="100px" label="登陆账号" align="center" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <span v-if='scope.row.user&&scope.row.user.userName'>{{scope.row.user.userName}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="telephone" min-width="85px" label="手机号" align="center" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <span v-if='scope.row.archive&&scope.row.archive.telephone'>{{scope.row.archive.telephone}}</span>
                  </template>
                </el-table-column>
                <el-table-column min-width="200px" prop="positions" label="归属关系" align="left">
                  <template slot-scope="scope">
                    <el-tag style="cursor: pointer;margin-left: 5px;" size="mini" :key=index v-for="(item,index) in scope.row.positions">{{item.posiName}}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="control" align="center" width="110px" label="操作" fixed="right">
                  <template slot-scope="scope">
                    <el-button title="编辑" class="td-btn-icon" type="text" @click="handleEdit(scope.$index, scope.row)"><i
                        class="el-icon-edit"></i></el-button>
                    <el-button class="td-btn-icon" type="text" title="删除" @click="handleDelete(scope.$index, scope.row)"
                      icon="el-icon-delete"></el-button>
                  </template>
                </el-table-column>
                <el-table-column prop="order" align="center" width="110px" label="排序" fixed="right">
                  <template slot-scope="scope">
                    <el-button class="td-btn-icon" type="text" v-if="scope.$index != 0" @click="handleUp(scope.$index, scope.row, 'up')"><i
                        class="el-icon-top"></i></el-button>
                    <el-button class="td-btn-icon" type="text" v-if="scope.$index != tableData.length-1" @click="handleUp(scope.$index, scope.row, 'down')"><i
                        class="el-icon-bottom"></i></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <!-- 分页 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" background
              :current-page="currentPage" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
          </el-tab-pane>
          <!-- 岗位-->
          <el-tab-pane label="岗位" name="second" class="el-flex el-box-column" lazy>
            <el-form style="float: left;height:43px" @submit.native.prevent>
              <el-form-item style="float:right">
                <el-button type="primary" @click='handleAddjob' plain>
                  新增
                  <i class="el-icon-plus"></i>
                </el-button>
              </el-form-item>
            </el-form>
            <div class="el-flex el-box-column">
              <el-table border class='el-flex' height="100%" width='100%' :data="tableJobData" stripe ref="tableJobData">
                <el-table-column type="index" min-width="50px" label="序号" align="center" sortable show-overflow-tooltip></el-table-column>
                <el-table-column prop="posiName" min-width="100px" label="岗位名称" align="center" sortable
                  show-overflow-tooltip></el-table-column>
                <el-table-column prop="desc" min-width="70px" label="描述" align="center" sortable show-overflow-tooltip></el-table-column>
                <el-table-column prop="status" min-width="70px" label="状态" align="center" sortable
                  show-overflow-tooltip>
                  <template slot-scope="scope">
                    <el-switch v-model="scope.row.status" active-value="Y" inactive-value="N" @change="switchChange(scope.row)"></el-switch>
                  </template>
                </el-table-column>
                <el-table-column prop="control" align="center" label="操作" fixed="right" width='150px'>
                  <template slot-scope="scope">
                    <el-button class="td-btn-icon" type="text" title="编辑" @click='handleJobEdit(scope.$index, scope.row)'
                      icon="el-icon-edit"></el-button>
                    <el-button class="td-btn-icon" type="text" title="删除" @click.native.prevent="deleteJobRow(scope.$index, scope.row)"
                      icon="el-icon-delete"></el-button>
                    <el-button class="td-btn-icon" :disabled="scope.row.status=='N'" type="text" title="关联人员"
                      @click.native.prevent="relatedStaffRow(scope.$index, scope.row)" icon="el-icon-link"></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <!-- 新增/编辑-->
            <el-dialog :title="dialogTitle" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="jobDialogVisible">
              <el-form label-width="150px" ref="editJobData" :model="editJobData">
                <el-form-item label="岗位名称" prop="posiName" :rules="{required: true, message: '岗位名称'}">
                  <el-col :span="12">
                    <el-input v-model="editJobData.posiName" auto-complete="off" placeholder="请填写岗位名称"></el-input>
                  </el-col>
                </el-form-item>
                <el-form-item label="隶属组织">
                  <el-col :span="12">
                    {{orgName}}
                  </el-col>
                </el-form-item>
                <el-form-item label="描述">
                  <el-col :span="12">
                    <el-input v-model="editJobData.desc" type="textarea" :rows="2" auto-complete="off" placeholder="请填写描述"></el-input>
                  </el-col>
                </el-form-item>
                <el-form-item label="状态">
                  <el-col :span="12">
                    <el-radio-group v-model="editJobData.status">
                      <el-radio label="Y">启用</el-radio>
                      <el-radio label="N">禁用</el-radio>
                    </el-radio-group>
                  </el-col>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="addOrEdit('editJobData')">保存 <i class="el-icon-document-checked"></i></el-button>
                <el-button type="danger" @click="handleAddSaveClose">取消 <i class="el-icon-close"></i></el-button>
              </span>
            </el-dialog>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-main>
    <!--岗位选择人员信息弹框  -->
    <el-dialog title="选择人员" :visible.sync="userVisible" class="demo-ruleForm" custom-class="el-dialog-flex"
      :close-on-click-modal="false" :close-on-press-escape="false">
      <div>
        <el-form @submit.native.prevent>
          <el-form-item>
            <el-input clearable v-model="jobPersonalSearch" placeholder="请输用人员名称" style="width:280px;"
              @keyup.enter.native="employeeTableSearchs" @clear="clearEmployeeTableSearchFun">
              <el-button slot="append" icon="el-icon-search" @click="employeeTableSearchs"></el-button>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div style='overflow: auto;'>
        <el-table :data="userTableData" border highlight-current-row ref="userTableData" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column min-width="85px" align="center" sortable :show-overflow-tooltip="true" property="empName"
            label="人员姓名"></el-table-column>
          <el-table-column min-width="70px" sortable :show-overflow-tooltip="true" property="empCode" label="人员代码"></el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <el-pagination background @size-change="handleSizeUserChange" :current-page="currentUserPage" @current-change="handleCurrentUserChange"
        :page-size="pageUserSize" layout="total, sizes, prev, pager, next, jumper" :total="totalUser"></el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleUserSure"> 确定<i class="el-icon-document-checked el-icon--right"></i></el-button>
        <el-button type="danger" @click="userVisible=false">关闭 <i class="el-icon-close"></i></el-button>
      </span>
    </el-dialog>
    <!-- 从档案中选择人员 -->
    <ChooseArchivesPerson :dialogPersonnelVisible="dialogPerson" :multiple='multipleSelect' @dialogEmployeesData="dialogissuerCheckSure" />
  </el-container>
</template>
<script>
  import {
    Tree,
    Dialog,
    Table,
    TableColumn,
    Pagination,
    MessageBox,
    Message,
    Tag,
    Upload,
    Popover,
    Tabs,
    TabPane,
    Radio,
  } from 'element-ui'
  import {
    employeeTable, //查询员工信息
    employeeTableSearch, // 查询员工信息（支持按员工姓名模糊查询）
    deleteEmployee, // 删除员工信息
    getPositionTable, // 查询指定组织下的岗位列表
    addPositionTable, // 新增岗位信息
    editPositionTable, // 修改岗位信息
    deltPositionTable, // 删除岗位信息
    moveEmployee, //人员移动
    saveArchivesId, //批量保存员工与组织的隶属关系
    saveEmpIds, //批量保存员工与岗位的分配关系
  } from '@/api/org/peopleManages/peopleManages.js'
  import {
    comboBoxDataSelect, //下拉通用接口
  } from '@/api/org/orgnizationArchives/orgnizationArchives.js'
  import ChooseArchivesPerson from './chooseArchivePerson'
  import {
    treeRoot, //组织树根节点
    childrenTree, //父级组织下的下级组织
    searchTree, //组织树查询
  }
  from '@/api/org/organizationTree/organizationTree.js'
  export default {
    name: 'peopleManages',
    components: {
      'el-tree': Tree, //树形菜单
      'el-dialog': Dialog, //对话框
      'el-table': Table, //表格
      'el-table-column': TableColumn, //表格列
      'el-pagination': Pagination, //分页
      'el-tag': Tag, //标签
      'el-upload': Upload,
      'el-popover': Popover,
      'el-image': Image,
      'el-tabs': Tabs, // 标签页
      'el-tab-pane': TabPane, // 标签页列
      'el-radio': Radio, // 标签页列
      ChooseArchivesPerson
    },

    data() {
      return {
        node: [],
        resolve: [],
        selectTreeBox: true, //下拉树
        selectTreeId: '', //下拉树Id
        selectTreeItem: {}, //下拉选中树节点
        rootTreeData: [], //树根节点数据
        multipleSelect: 'Y', //关联人员多选
        currentPositionId: '',
        currentEmpIds: [],
        currentOrgId: "", //当前组织Id
        currentUserPage: 1, //岗位关联人员弹框当前页数
        totalUser: 20, //岗位关联人员弹框总条数
        pageUserSize: 20, //岗位关联人员弹框条数
        userVisible: false, //岗位关联人员弹框
        userTableData: [], //岗位关联人员弹框表格
        rowStaffDialog: '', //false
        currentTreeId: '', //当前TreeId
        dialogPerson: false, //从人员档案中选人弹框
        dialogStaff: false,
        searchTreeData: [], //搜索返回的树形数据
        currentUserId: "", //当前用户Userid
        treeKey: 0, //树key
        orgNameSearch: '', //树模糊搜索
        currentNodekey: "", //默认选中的节点树
        expandedkeys: [], //默认展开的节点树
        treeExpandedKey: [],
        changeTitle: "",
        keyTree: 1,
        dataTree: [], //树形图初始化
        defaultProps: {
          label: 'orgName',
          isLeaf: 'leaf'
        },
        dialogVisible: false, //岗位编辑弹框
        currentPage: 1, //人员信息当前页
        pageSize: 20, //人员信息当前页条数
        total: 0, //人员信息总条数
        Authorization: '',
        editData: {},
        dialogPeople: false,
        personalName: "",
        tableData: [], //树形图初始数据
        orgId: "",
        addUser: [], //下拉人员初始化
        addGender: [], //下拉性别
        personalSearch: '', //人员搜索字眼,
        initialeditData: {},
        justJobEdit: '',
        activeName: 'first',
        tableJobData: [], //岗位表格
        editJobData: {}, //岗位弹框
        jobDialogVisible: false, //岗位弹框
        dialogTitle: '', //岗位弹框标题
        jobTotal: '', //岗位总数据
        orgName: '', //隶属组织名
        jobPersonalSearch: '', //岗位信息弹框人员搜索字眼
        personalSearchType: 'N', //人员信息搜索（N无搜索，Y搜索）
        jobPersonalSearchType: 'N', //岗位弹框人员信息搜索（N无搜索，Y搜索）
        tableGener: '', //表格性别
        tableTelephone: '', //表格电话
        staffStatusDatas: [], //人员状态
        initTree:false,//初始化树的加载
      }
    },
    watch: {
      orgNameSearch(val) { //搜索
        let data = {
          name: val,
          userId: this.currentUserId,
          treeId: this.selectTreeId
        }
        if (val) {
          searchTree(data).then(res => {
            let datas = res.data.data;
            this.removeTip() //移除默认提示
            this.deepChild(datas);
            this.searchTreeData = datas;
          });
        } else {
          this.treeKey += 1;
        }
      }
    },
    created() {
      this.getRootTree()
      this.getStaffStatus()
      this.currentUserId = this.$store.state.userInfo.userId
      this.Authorization = this.getCookie('Authorization')
      window.onresize = () => {
        this.$refs.tableData.doLayout()
      }
    },
    methods: {
      getStaffStatus() { //员工状态
        comboBoxDataSelect('b290dcb8255049b1b3b6ca672eaabb9a').then(res => {
          if (res.data.code == 10000) {
            this.staffStatusDatas = res.data.data
          }
        })
      },
      getCookie(cname) { // 获取cookie
        var name = cname + "="
        var ca = document.cookie.split(';')
        for (var i = 0; i < ca.length; i++) {
          var c = ca[i].trim()
          if (c.indexOf(name) == 0) return c.substring(name.length, c.length)
        }
        return ""
      },
      removeTip() { //移除默认提示
        let msgs = document.getElementsByClassName("el-message")
        for (let i = 0, len = msgs.length; i < len; i++) {
          msgs[i].style.display = "none";
        }
      },
      deepChild(val) { //递归遍历树形数据源
        let $this = this;
        if (val && Array.isArray(val) && val.length) {
          val.forEach(item => {
            if (typeof item === 'object') {
              item.orgName = item.name;
              $this.deepChild(item.children);
            }
          })
        }
      },
      getRootTree() { //获取树根节点
        treeRoot().then(res => {
          if (res.data.code == 10000) {
            let resDatas = res.data.data
            this.selectTreeId = resDatas[0].treeId
            this.rootTreeData = resDatas
            this.initTree = true
          }
        })
      },
      changSelectTree(val) { //树下拉切换
        this.node.childNodes = []
        this.loadNode(this.node, this.resolve)
      },
      treeSearch() { //组织树搜索
        this.selectTreeBox = false
        this.$nextTick(() => {
          this.$refs.searchFcus.focus()
        })
      },
      searchBlur() { //树搜索失焦
        this.selectTreeBox = true
        this.orgNameSearch = ''
      },
      loadNode(node, resolve) { //组织树懒加载
        if (node.level == 0) {
          this.node = node
          this.resolve = resolve
          // if (!this.selectTreeId) {
          //   this.selectTreeId = 1527
          // }
          childrenTree(this.selectTreeId).then(res => {
            if (res.data.code == 10000) {
              let data = res.data.data
              data.forEach(item => {
                item.label = item.orgName
                item.id = item.treeId
                item.isLeaf = item.isLeaf == 'n' ? false : true
              })
              if (data.length > 0) {
                this.currentNodekey = data[0].treeId
                this.currentTreeId = data[0].treeId
                this.currentOrgId = data[0].orgId
                this.expandedkeys.push(data[0].treeId)
                this.orgName = res.data.data[0].orgName
                this.originalEmployeeTableFun()
                this.getPositions()
                this.$nextTick(() => {
                  this.$refs.tree.setCurrentKey(this.currentNodekey)
                })

                this.editButtonShow = true
              } else {
                this.editButtonShow = false
              }
              return resolve(data)
            }
          })
        } else {
          childrenTree(node.data.treeId).then(res => {
            if (res.data.code == 10000) {
              let data = res.data.data
              data.forEach(item => {
                item.label = item.orgName
                item.id = item.treeId
                item.isLeaf = item.isLeaf == 'n' ? false : true
              })
              return resolve(data)
            }
          })
        }
      },
      // loadNode(node, resolve) { //组织树懒加载
      //   if (node.level == 0) {
      //     treeRoot().then(res => {
      //       if (res.data.code == 10000) {
      //         let data = res.data.data
      //         data.forEach(item => {
      //           item.label = item.orgName
      //           item.id = item.treeId
      //           item.isLeaf = item.isLeaf == 'n' ? false : true
      //         })
      //         if (data.length > 0) {
      //           this.currentNodekey = data[0].treeId
      //           this.currentTreeId = data[0].treeId
      //           this.currentOrgId = data[0].orgId
      //           this.expandedkeys.push(data[0].treeId)
      //           this.orgName = res.data.data[0].orgName
      //           this.originalEmployeeTableFun()
      //           this.getPositions()
      //           this.$nextTick(() => {
      //             this.$refs.tree.setCurrentKey(this.currentNodekey)
      //           })
      //         }
      //         return resolve(data)
      //       }
      //     });
      //   } else {
      //     childrenTree(node.data.treeId).then(res => {
      //       if (res.data.code == 10000) {
      //         let data = res.data.data
      //         data.forEach(item => {
      //           item.label = item.orgName
      //           item.id = item.treeId
      //           item.isLeaf = item.isLeaf == 'n' ? false : true
      //         })
      //         return resolve(data)
      //       }
      //     })
      //   }
      // },
      originalPage() { //页面初始化
        this.currentPage = 1
        this.pageSize = 20
      },
      employeeTableFun() { //查询员工信息通用方法
        this.personalSearchType = 'N'
        let data = {
          page: this.currentPage,
          size: this.pageSize,
          treeId: this.currentTreeId
        }
        employeeTable(data).then(res => {
          if (res.data.code == 10000) {
            this.tableData = res.data.data.records
            this.total = res.data.data.total
          }
        })
      },
      originalEmployeeTableFun() { //查询员工信息初始化
        this.originalPage()
        this.employeeTableFun()
      },
      employeeTableSearchEvent() { //人员搜索通用方法
        this.personalSearchType = 'Y'
        let data = {
          page: this.currentPage,
          size: this.pageSize,
          treeId: this.currentTreeId,
          name: this.personalSearch
        }
        employeeTableSearch(data).then(res => {
          if (res.data.code == 10000) {
            this.tableData = res.data.data.records
            this.total = res.data.data.total
          }
        })
      },
      originalEmployeeTableSearch() { //人员信息搜索
        this.originalPage()
        this.employeeTableSearchEvent()
      },
      clearSeachPeople() { //人员信息搜索清空
        this.personalSearch = ''
        this.originalEmployeeTableFun()
      },
      handleNodeClick(val) { //点击树
        if (val.treeId) {
          this.currentTreeId = val.treeId
        } else {
          this.currentTreeId = val.id
        }
        this.currentOrgId = val.orgId
        this.orgName = val.orgName
        this.originalEmployeeTableFun()
        this.getPositions()
      },
      handlePeopleEdit(index, row) { //人员岗位编辑
        this.dialogPeople = true
        this.justJobEdit = 'true'
        this.$nextTick(() => {
          this.editData = JSON.parse(JSON.stringify(row))
          this.initialeditData = JSON.parse(JSON.stringify(this.editData))
        })
      },
      jobEdit(data) {
        this.editData.positions = data
      },
      handleUp(index, row, isUp) { //向上移动
        if (isUp == 'up') {
          let data = {
            'empId': row.empId,
            'treeId': this.currentTreeId,
            'type': 1
          }
          moveEmployee(data).then(res => {
            if (res.data.code == 10000) {
              this.originalEmployeeTableFun()
            }
          })
        } else { //向下移动
          let data = {
            'empId': row.empId,
            'treeId': this.currentTreeId,
            'type': 2
          }
          moveEmployee(data).then(res => {
            if (res.data.code == 10000) {
              this.originalEmployeeTableFun()
            }
          })
        }
      },
      jumpRouter(row) { //动态路由跳转
        this.$router.addRoutes(this.multiRouters([{
          path: 'editOrAddPeopleManages',
          name: 'editOrAddPeopleManages', //自定义name名称
          component: () => import('@/views/org/peopleManages/editOrAddPeopleManages'),
          meta: {}
        }]));
        this.$router.push(this.routerMatch({
          name: "editOrAddPeopleManages", //顶部导航+侧边导航
          params: {
            row: row,
            treeId: this.currentTreeId,
            orgId: this.currentOrgId,
            orgName: this.orgName
          }
        }))
      },
      handleAdd() { //新增按钮
        let row = {
          title: '新增'
        }
        this.jumpRouter(row)
      },
      handleEdit(index, row) {
        row.title = '编辑'
        this.jumpRouter(row)
      },
      pageSameFun() { //分页相同方法
        if (this.personalSearchType == 'N') {
          this.employeeTableFun()
        } else {
          this.employeeTableSearchEvent()
        }
      },
      handleSizeChange(val) { //人员信息条数切换
        this.pageSize = val
        this.pageSameFun()
      },
      handleCurrentChange(val) { //人员信息页数切换
        this.currentPage = val
        this.pageSameFun()
      },
      getPositions() { //获取当前机构下岗位
        let data = {
          treeId: this.currentTreeId,
        }
        getPositionTable(data).then(res => {
          if (res.data.code == 10000) {
            this.tableJobData = res.data.data
          }
        })
      },
      relatedStaff() { //关联员工
        this.dialogPerson = true
      },
      deleteJobRow(index, row) { //岗位删除
        MessageBox.confirm('您是否确定删除选中内容', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deltPositionTable(row.positionId).then(res => {
            if (res.data.code == 10000) {
              this.getPositions()
              Message({
                type: 'success',
                message: '删除成功！'
              })
            }
          })
        })
      },
      handleAddjob() { //岗位新增
        this.dialogTitle = '新增'
        this.editJobData = {
          posiName: '',
          status: 'Y',
          desc: '',
        }
        if (this.$refs.editJobData != undefined) {
          this.$refs.editJobData.resetFields()
        }
        this.jobDialogVisible = true
      },
      handleJobEdit(index, row) { //岗位编辑
        this.dialogTitle = '编辑'
        this.jobDialogVisible = true
        this.$nextTick(() => {
          row.orgId = this.orgId
          this.editJobData = JSON.parse(JSON.stringify(row))
        })
      },
      handleDelete(index, row) { //人员删除
        MessageBox.confirm('您是否确定删除选中内容', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let data = {
            empId: row.empId,
            treeId: this.currentTreeId
          }
          deleteEmployee(data).then(res => {
            if (res.data.code == 10000) {
              this.originalEmployeeTableFun()
              Message({
                type: 'success',
                message: '删除成功！'
              })
            }
          })
        })
      },
      relatedStaffRow(index, row) { //岗位关联人员
        this.userVisible = true
        this.currentPositionId = row.positionId
        this.origianlStaffTableFun()
      },
      switchChange(row) { //岗位状态
        editPositionTable(row).then(res => {
          if (res.data.code == 10000) {
            Message({
              type: 'success',
              message: '操作成功！'
            })
            this.getPositions()
          }
        })
      },
      addOrEdit(formName) { //岗位确认
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.dialogTitle == '新增') {
              let data = {
                treeId: this.currentTreeId,
                posiName: this.editJobData.posiName,
                status: this.editJobData.status,
                desc: this.editJobData.desc,
              }
              addPositionTable(data).then(res => {
                if (res.data.code == 10000) {
                  Message({
                    type: 'success',
                    message: '保存成功！'
                  })
                  this.getPositions()
                  this.jobDialogVisible = false
                }
              })
            } else {
              editPositionTable(this.editJobData).then(res => {
                if (res.data.code == 10000) {
                  Message({
                    type: 'success',
                    message: '保存成功！'
                  })
                  this.getPositions()
                  this.jobDialogVisible = false
                }
              })
            }
          }
        });
      },
      origianlStaffPage() { //岗位弹框员工信息分页初始化
        this.currentUserPage = 1
        this.pageUserSize = 20
      },
      staffTableFun() { //查询岗位弹框员工信息通用方法
        this.jobPersonalSearchType = 'N'
        let data = {
          page: this.currentUserPage,
          size: this.pageUserSize,
          treeId: this.currentTreeId
        }
        employeeTable(data).then(res => {
          if (res.data.code == 10000) {
            let resDatas = res.data.data.records
            let newDatas = []
            resDatas.forEach(item => {
              let itemPositions = item.positions
              let itemPositionsIds = []
              itemPositions.forEach(pItems => {
                itemPositionsIds.push(pItems.positionId)
              })
              if (!itemPositionsIds.includes(this.currentPositionId)) {
                newDatas.push(item)
              }
            })
            this.userTableData = newDatas
            this.totalUser = newDatas.length
          }
        })
      },
      origianlStaffTableFun() { //查询岗位弹框员工信息初始化
        this.origianlStaffPage()
        this.staffTableFun()
      },
      employeeTableSearchFun() { //查询岗位弹框人员搜索通用方法
        this.jobPersonalSearchType = 'Y'
        let data = {
          page: this.currentUserPage,
          size: this.pageUserSize,
          treeId: this.currentTreeId,
          name: this.jobPersonalSearch
        }
        employeeTableSearch(data).then(res => {
          if (res.data.code == 10000) {
            let resDatas = res.data.data.records
            let newDatas = []
            resDatas.forEach(item => {
              let itemPositions = item.positions
              let itemPositionsIds = []
              itemPositions.forEach(pItems => {
                itemPositionsIds.push(pItems.positionId)
              })
              if (!itemPositionsIds.includes(this.currentPositionId)) {
                newDatas.push(item)
              }
            })

            this.userTableData = newDatas
            this.totalUser = newDatas.length
          }
        })
      },
      employeeTableSearchs() { //查询岗位弹框人员搜索
        this.origianlStaffPage()
        this.employeeTableSearchFun()
      },
      clearEmployeeTableSearchFun() { //查询岗位弹框人员搜索清除
        this.jobPersonalSearch = ''
        this.origianlStaffTableFun()
      },
      userPageSame() { //岗位弹框表格人员分页相同方法
        if (this.jobPersonalSearchType == 'N') {
          this.staffTableFun()
        } else {
          this.employeeTableSearchFun()
        }
      },
      handleSizeUserChange(val) { //岗位弹框表格人员条数切换
        this.pageUserSize = val
        this.userPageSame()
      },
      handleCurrentUserChange(val) { //岗位弹框表格人员页数切换
        this.currentUserPage = val
        this.userPageSame()
      },
      handleAddSaveClose() { //岗位关闭
        this.jobDialogVisible = false
      },
      saveArchivesIdEvent(treeId, data) { //批量保存
        saveArchivesId(treeId, data).then(res => {
          if (res.data.code == 10000) {
            Message({
              'message': '保存成功！',
              'type': 'success'
            })
            this.originalEmployeeTableFun()
          }
        })
      },
      dialogissuerCheckSure(data) { //子传父
        this.dialogPerson = false
        if (!data) {
          return
        }
        let ary = []
        data.forEach(item => {
          ary.push(item.humanArchId)
        })
        let datas = {
          archiveIds: ary
        }
        this.saveArchivesIdEvent(this.currentTreeId, ary)
      },
      saveEmpIdsEvent(positionId, empIds) {
        saveEmpIds(positionId, empIds).then(res => {
          if (res.data.code == 10000) {
            Message({
              message: '关联成功!',
              type: 'success'
            })
            this.userVisible = false
          }
        })
      },
      handleSelectionChange(val) { //员工与岗位批量关联
        let ids = []
        val.forEach(item => {
          ids.push(item.empId)
        })
        this.currentEmpIds = ids
      },
      handleUserSure() { //岗位关联员工弹框确认
        this.saveEmpIdsEvent(this.currentPositionId, this.currentEmpIds)
      },
    }
  };
</script>

<style lang="scss">
  .el-tag {
    margin-bottom: 3px !important;
  }

  .el-card__body {
    position: relative;
  }

  .pagination.el-pagination {
    position: absolute;
    bottom: 5px;
    left: 15px;
  }

  .el-form-tag .el-tag {
    margin-bottom: 10px;
    margin-left: 0 !important;
    margin-right: 10px !important;
  }

  .table-title-word {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .people-photo {
    .el-upload-list__item-preview {
      display: none !important;
    }
  }

  .top-select {
    width: 250px;
  }
</style>
